﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GPMS.Web.Helpers
{
    using GPMS.Model;
    using System.Web.Security;

    /// <summary>
    /// 用户辅助类
    /// </summary>
    public static class UserHelper
    {
        /// <summary>
        /// 检查是否登陆
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool IsLogin(HttpContextBase context)
        {
            return context.User.Identity.IsAuthenticated;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        /// <param name="gpms"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        public static bool SignIn(LoginVM model, GPMSDbContainer gpms, HttpResponseBase response)
        {
            var users = gpms.UserInfos.Where(SelectParameter(model));
            if (users.Count() > 0)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    users.FirstOrDefault().UserName,
                    DateTime.Now,
                    DateTime.Now.AddDays(7),
                    true,
                    users.FirstOrDefault().UserID.ToString());
                response.SetCookie(new HttpCookie(FormsAuthentication.FormsCookieName,
                    FormsAuthentication.Encrypt(ticket)));
                return true;
            }
            else
            {
                return false;
            }
        }

        private static Func<UserInfo, bool> SelectParameter(LoginVM model)
        {
            Func<UserInfo, bool> func;
            Func<UserInfo, bool> funcCommon = user => 
                user.Password == model.Password &&
                user.IsDeleted == false &&
                user.IsLocked == false;
            if (model.LoginType.Equals("userName"))
            {
                func = user => user.UserName == model.User && funcCommon(user);
            }
            else
            {
                func = user => user.UserIdentity == model.User && funcCommon(user);
            }
            return func;
        }

        /// <summary>
        /// 登出
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}